import React, { Component } from 'react';
import { Row, Col, Icon, Button, Input, Pagination, message, Modal, List } from 'antd';
import "antd/dist/antd.css";
import { withRouter } from 'react-router'
import Header from '../../common/header'
import Footer from '../../common/footer';
import Extend from './extend'
import NotExtend from './notExtend'
import './index.scss';
import { getSongData, getSongComment, getSongLyric, getSongUrlData, setSongComment, getSongSheetByUserId, setSongSheet } from '../../api';
import { formatHotCommentPublishTime } from '../../api/formatData'
import docCookies from '../../api/docCookies';
const { TextArea } = Input;


class Song extends Component {

    constructor(props){
        super(props);
        this.state = {
            isExtend: false,  //用于确定歌词是否展开
            comment: "",
            collectModalVisible: false,

            songId: 0,
            songName: "",
            picUrl: "",
            singer: {
                singerId: 0,
                singerName: ""
            },
            label: [],
            album: {
                albumId: 0,
                albumName: ""
            },
            allComment: [],
            commentTotal: 0,
            lyric: "",
            songSheet: [
                {id:1, name:'歌单1'},
                {id:2, name:'歌单2'},
                {id:3, name:'歌单3'}
            ]

        }
    }


    componentDidMount(){
        // 获取歌曲id
        const searchStr = this.props.location.search.match(/\d+/gi).toString();
        this.searchStr = searchStr;
        this.csrf = localStorage.getItem("token")  || docCookies.getItem("__csrf");;
        console.log(this.csrf)

        // 获取歌曲信息
        getSongData(parseInt(searchStr)).then((res)=>{
            const song = res.data.songs[0];
            this.setState({
                songId: song.id,
                songName: song.name,
                picUrl: song.picUrl,
                singer: song.singer[0],
                label: song.label,
                album: song.album,
            })
        });

        // 获得歌曲评论数据
        getSongComment(searchStr).then((res)=>{
            const allComment = res.data.comments;
            this.setState({
                allComment,
                commentTotal: res.data.total
            })
        });

        // 获取单曲歌词数据
        getSongLyric(searchStr).then((res)=>{
            const lyric = res.data.lrc.lyric;
            this.setState({
                lyric
            })
        });

        if(this.csrf) {
            console.log("判断")
            let userId = JSON.parse(localStorage.getItem('loginObj')).userId
            getSongSheetByUserId(userId).then((res)=>{
                const songSheet = res.data.songSheet;
                this.setState({
                    songSheet
                })
            })
        }


    }


    handleFresh = () => {

        const searchStr = this.props.location.search.match(/\d+/gi).toString();
        this.searchStr = searchStr;
        this.csrf = localStorage.getItem("token")  || docCookies.getItem("__csrf");;

        // 获取歌曲信息
        getSongData(parseInt(searchStr)).then((res)=>{
            const song = res.data.songs[0];
            this.setState({
                songId: song.id,
                songName: song.name,
                picUrl: song.picUrl,
                singer: song.singer[0],
                label: song.label,
                album: song.album,
            })
        });

        // 获得歌曲评论数据
        getSongComment(searchStr).then((res)=>{
            const allComment = res.data.comments;
            this.setState({
                allComment,
                commentTotal: res.data.total
            })
        });

        // 获取单曲歌词数据
        getSongLyric(searchStr).then((res)=>{
            const lyric = res.data.lrc.lyric;
            this.setState({
                lyric
            })
        });

        if(this.csrf) {
            console.log("判断")
            let userId = JSON.parse(localStorage.getItem('loginObj')).userId
            getSongSheetByUserId(userId).then((res)=>{
                const songSheet = res.data.songSheet;
                this.setState({
                    songSheet
                })
            })
        }
    }


    itemRender = (current, type, originalElement) => {
        if(type==='prev') {
            return <a>上一页</a>
        }if(type==='next') {
            return <a>下一页</a>
        }
        return originalElement
    };


    handleExtendLyric = (boo) => {
        this.setState({
            isExtend: boo
        })
    };


    handleChange = (current, size) => {
        const searchStr = this.props.location.search.match(/\d+/gi).toString();
        getSongComment(searchStr,size,current).then( (res)=>{
            this.props.songCommentDataFunc(res.data)
        } )
    };


    // 开始播放歌曲
    startPlaySong = () => {

        const searchStr = this.props.location.search.match(/\d+/gi).toString();
        // 传递一个歌曲id给MusicPlayer
        let songId = parseInt(searchStr)

        getSongUrlData(songId).then( (res) => {
            if(res.data.code === 200) {
                let arr = [];
                let storage =  JSON.parse(localStorage.getItem("songUrlData"));
                if(!storage) {
                    arr.push(res.data.data[0])
                    localStorage.setItem('songUrlData',JSON.stringify(arr))
                } else {
                    storage.push(res.data.data[0])
                    localStorage.setItem("songUrlData",JSON.stringify(storage))
                }
                docCookies.setItem("playing","PLAYING");
                this.forceUpdate();
            }else {
                message.info("请求数据失败")
            }
        } );


        // 请求歌曲,歌手的播放信息
        getSongData(songId).then( (res) => {
            if(res.data.code===200) {
                let arr = [];
                let storage =  JSON.parse(localStorage.getItem("songInfoData"));
                if(!storage) {
                    arr.push(res.data.songs[0])
                    localStorage.setItem('songInfoData',JSON.stringify(arr))
                    this.forceUpdate();
                }else {
                    storage.push(res.data.songs[0])
                    localStorage.setItem("songInfoData",JSON.stringify(storage))
                }
            }else {
                message.info("请求歌手歌曲数据失败,请重新尝试")
            }
        })

    };


    handleCommentClick = () => {
        const {comment, songId} = this.state;
        let userId = JSON.parse(localStorage.getItem('loginObj')).userId

        setSongComment(userId, comment, new Date().getTime(), songId).then((res)=>{
            this.props.songCommentDataFunc(res.data)
        });

        this.setState({
            comment: ""
        })

        this.handleFresh();

    };


    onInputChange = e => {
        console.log(e.target.value)
        this.setState({
            comment: e.target.value,
        })
    };

    showCollectModal = () => {
        this.setState({
            collectModalVisible: true,
        });
    };

    handleCollectModalOk = e => {
        this.setState({
            collectModalVisible: false,
        });
    };

    handleCollectModalCancel = e => {
        this.setState({
            collectModalVisible: false,
        });
    };

    handleAddSongSheet = (item) => {
        this.setState({
            collectModalVisible: false,
        });

        // 收藏到歌单
        setSongSheet(item.id, this.state.songId).then((res)=>{
            message.info('收藏成功');
        });

    }

    // 添加歌曲到歌单列表
    addToPlayList = () => {

        const {songId} = this.state;

        getSongUrlData(songId).then( (res) => {
            if(res.data.code === 200) {
                let arr = [];
                let storage =  JSON.parse(localStorage.getItem("songUrlData"));
                if(!storage) {
                    arr.push(res.data.data[0])
                    localStorage.setItem('songUrlData',JSON.stringify(arr))
                } else {
                    storage.push(res.data.data[0])
                    localStorage.setItem("songUrlData",JSON.stringify(storage))
                }
                docCookies.setItem("playing","PLAYING");
                this.forceUpdate();
            }else {
                message.info("请求数据失败")
            }
        } );


        // 请求歌曲,歌手的播放信息
        getSongData(songId).then( (res) => {
            if(res.data.code===200) {
                let arr = [];
                let storage =  JSON.parse(localStorage.getItem("songInfoData"));
                if(!storage) {
                    arr.push(res.data.songs[0])
                    localStorage.setItem('songInfoData',JSON.stringify(arr))
                    this.forceUpdate();
                }else {
                    storage.push(res.data.songs[0])
                    localStorage.setItem("songInfoData",JSON.stringify(storage))
                }
            }else {
                message.info("请求歌手歌曲数据失败,请重新尝试")
            }
        })

    }


    render() {

        const {songId, songName, picUrl, singer, label, album, allComment, commentTotal, lyric, comment} = this.state;

        // 去除时间和/n得格式化歌词
        const html = lyric && lyric.replace(/\[\d+:\d+\.\d+\]/gi,"").replace(/\n/gi,"<br />");

        //渲染评论
        const renderComment =  allComment.length > 0
            ?
            allComment.map( (item,index,arr)=>{
                //对返回的数据中的/n进行替换，替换成<br/>标签
                const str = item.content.replace(/\n/g,'<br />');
                //去除最后一条评论的borderbottom
                const showBorder = index === arr.length-1 ? false : true;
                return (
                    <div className='newComment' style={{marginBottom:"25px"}}>
                        <span className='avatar' style={{backgroundImage:`url(${"http://cyq.center:8000/"+item.user.userPicUrl})`}}></span>
                        <span className='userComment'>
                            <span style={{ color:"#1679C5",fontSize:"12px" }}>{item.user.nickname}</span>
                            <span style={{ fontSize:"12px" }} dangerouslySetInnerHTML={{__html: str}}></span>
                        </span>
                        <span className='commentTime'>{formatHotCommentPublishTime(item.time)}</span>
                    </div>
                )
            })
            :
            null;

        return (
            <div className='song'>
                <div style={{ backgroundColor:"#242400",color:"#fff",position:"fixed",zIndex:10,top:"0",width:"100%" }}>
                    <Header />
                </div>
                <div>
                    {/* <MusicPlay/> */}
                </div>
                <div className='song-content' style={ { marginTop:"13vh",minWidth:"1430px" } }>
                    <Row>
                        <Col span={10}>
                            <Row>
                                <Col span={24}>
                                    <div className='song-logo' style={{marginLeft: "100px"}}>
                                        <div className='song-logo-img'>
                                            <img  src={"http://cyq.center:8000/"+picUrl} alt="" />
                                        </div>
                                    </div>
                                </Col>
                            </Row>
                            <Row style={{marginTop:"150px", marginLeft:"130px"}}>
                                <div className="playText" onClick={()=>this.startPlaySong()} style={{marginRight:"15px"}}>
                                    播放
                                </div>
                                <div className='playText' onClick={this.addToPlayList} style={{marginRight:"15px"}}>
                                    添加
                                </div>
                                {
                                this.csrf
                                ?
                                    <div className='playText' onClick={this.showCollectModal}>
                                        收藏
                                    </div>
                                :
                                    null
                                }
                            </Row>
                        </Col>
                        <Col span={12} style={{ backgroundColor:"#fff", borderTop:"none",paddingBottom:"90px", marginTop:"50px" }}>
                            <Row>
                                {/* //内容左侧 */}
                                <div className='song-content-rightHeader'>
                                    <span className='song-content-rightHeader-name'>{songName}</span>
                                </div>
                                <div className='song-content-singer' style={{marginTop:"20px"}}>
                                    <span style={{ fontSize:"12px" }}>歌手:</span>
                                    {
                                        singer.singerName
                                        ?
                                        <span style={{ marginLeft:"5px", fontSize:"12px", color:"#2273C2" }}>{singer.singerName}</span>
                                        :
                                        null
                                    }

                                </div>
                                <div className='song-content-belongAlbum'>
                                    <span style={{ fontSize:"12px" }}>专辑:</span>
                                    <span style={{marginLeft:"5px",fontSize:"12px",color:"#2273C2" }}>{album.albumName}</span>
                                </div>
                                <div className='song-content-label'>
                                    <span style={{ fontSize:"12px" }}>标签:</span>
                                    {label.map( (item) => {
                                        return(
                                            <span style={{marginLeft:"5px",fontSize:"12px",color:"#2273C2" }}>{item.name}</span>
                                        )
                                    })}
                                </div>

                                {/*歌词*/}
                                {
                                    this.state.isExtend
                                        ?
                                        <Extend html={html} handleExtendLyric={(boo)=>this.handleExtendLyric(boo)} />
                                        :
                                        <NotExtend html={html} handleExtendLyric={(boo)=>this.handleExtendLyric(boo)}/>
                                }
                            </Row>
                        </Col>

                        <Col span={2}></Col>

                    </Row>

                    {
                        this.csrf
                        ?
                        <div>
                            {/*评论标题显示*/}
                            <Row>
                                <Col span={2}></Col>
                                <Col span={20}>
                                    <Row>
                                        <Col span={2}></Col>
                                        <Col span={16}>
                                            <div>
                                                <span
                                                    style={{ color:"#4C4C4C",fontSize:"20px",marginRight:"20px" }}
                                                >
                                                    评论
                                                </span>
                                                <span
                                                    style={{ color:"#6F6F6F",fontSize:"14px" }}

                                                >
                                                    共{commentTotal}条评
                                                </span>
                                            </div>
                                        </Col>
                                        <Col span={6}></Col>
                                    </Row>

                                </Col>
                                <Col span={2}></Col>
                            </Row>

                            {/*评论输入框*/}
                            <Row style={{marginTop:"30px"}}>
                                <Col span={2}></Col>
                                <Col span={20}>
                                    <Row>
                                        <Col span={2}>
                                            {/* <img src={defaultAvatar} width="30px" height="30px" alt=""/> */}
                                        </Col>
                                        <Col span={16} style={{ position:"relative" }}>
                                            <TextArea rows={4} onChange={this.onInputChange} value={comment}/>
                                            <span className='circle'>&nbsp;</span>
                                            <span className='circle-mask'>&nbsp;</span>
                                        </Col>
                                        <Col span={6}></Col>
                                    </Row>
                                </Col>
                                <Col span={2}></Col>
                            </Row>


                            <Row>
                                <Col span={16}></Col>
                                <Col span={8}>
                                    <div className="commentText" onClick={this.handleCommentClick}>评论</div>
                                </Col>
                            </Row>


                            <Row style={{marginTop:"40px"}}>
                                <Col span={2}></Col>
                                <Col span={18}>
                                    {
                                        allComment.length > 0
                                            ?
                                            <div style={{ marginLeft:"40px" }}>
                                                <div style={{paddingBottom:"20px"}}>
                                                    <span style={{ color:"#000",fontSize:"12px",fontWeight:"bold" }}>评论</span>
                                                    <span style={{ color:"#000",fontSize:"12px",fontWeight:"bold" }}>({commentTotal})</span>
                                                </div>
                                                {
                                                    renderComment
                                                }
                                            </div>
                                            :
                                            null
                                    }
                                </Col>
                                <Col span={4}></Col>
                            </Row>

                        </div>
                    :
                        null

                    }

                </div>

                <div>
                    <Footer />
                </div>


                <Modal
                    title='收藏到歌单'
                    visible={this.state.collectModalVisible}
                    onOk={this.handleCollectModalOk}
                    onCancel={this.handleCollectModalCancel}
                >
                    <List
                        size="small"
                        bordered
                        dataSource={this.state.songSheet}
                        renderItem={item =>
                            <List.Item
                                actions={[<a onClick={()=>this.handleAddSongSheet(item)}>添加</a>]}
                            >
                                {item.name}
                            </List.Item>
                        }
                    />
                </Modal>
            </div>
        )
    }
}


export default withRouter(Song)
